<template>
  <div class="app-container">
    <div class="settle-workbench">
      <!-- 统计卡片 -->
      <div class="workbench-cards">
          
        <div class="card-item card-1">
          <div class="card-header-h1">
            <div class="card-title">企业配置状态</div>
          </div>
          <div class="card-content">
            <div class="data-row">
              <div class="data-item" @click="handleCardClick('total')">
                <div class="data-label">企业总数量</div>
                <div class="data-value normal">{{ enterpriseStatus.totalCount }}</div>
              </div>
              <div class="data-item" @click="handleCardClick('unsettledConfig')">
                <div class="data-label">未结算配置企业数量</div>
                <div class="data-value">{{ enterpriseStatus.unsettledConfigCount }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="card-item card-2">
          <div class="card-header-h2">
            <div class="card-title">当前账期状态</div>
          </div>
          <div class="card-content">
            <div class="data-row">
              <div class="data-item" @click="handleCardClick('noData')">
                <div class="data-label">无采集数据企业数量</div>
                <div class="data-value">{{ periodStatus.noDataCount }}</div>
              </div>
              <div class="data-item" @click="handleCardClick('unsettled')">
                <div class="data-label">未结算企业数量</div>
                <div class="data-value">{{ periodStatus.unsettledCount }}</div>
              </div>
              <div class="data-item" @click="handleCardClick('unconfirmed')">
                <div class="data-label">未确认企业数量</div>
                <div class="data-value">{{ periodStatus.unconfirmedCount }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 企业信息区域 -->
      <div class="enterprise-section">
        <!-- 左侧：地点位置 -->
        <div class="manage-left">
          <el-label style="width: 100%;">地点位置</el-label>
          
          <el-tree 
            v-if="!locationLoading && locationTree.length > 0"
            :data="locationTree"
            :props="locationTreeProps"
            node-key="id"
            :highlight-current="true"
            @node-click="handleLocationClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>
                  <i v-if="data.type === 'building'" class="el-icon-office-building" style="color: #409eff; margin-right: 6px;"></i>
                  <i v-else-if="data.type === 'floor'" class="el-icon-menu" style="color: #67c23a; margin-right: 6px;"></i>
                  <i v-else-if="data.type === 'room'" class="el-icon-house" style="color: #e6a23c; margin-right: 6px;"></i>
                  {{ node.label }}
                </span>
              </span>
            </template>
          </el-tree>

          <div v-else-if="!locationLoading && locationTree.length === 0" class="empty-state">
            <p>暂无地点位置数据</p>
          </div>
        </div>

        <!-- 右侧：企业信息列表 -->
        <div class="manage-right">
          <!-- 查询条件 -->
          <div class="query-wrapper">
            <el-form :inline="true" :model="queryForm" class="query-form">
              <el-form-item label="企业简称" class="query-item query-item-1">
                <el-input v-model="queryForm.shortName" placeholder="请输入" clearable style="width:200px" />
              </el-form-item>
              <el-form-item label="结算周期" class="query-item query-item-2">
                <el-select v-model="queryForm.settlementCycle" placeholder="请选择" clearable style="width: 100px">
                  <el-option label="月结" value="month" />
                  <el-option label="季结" value="quarter" />
                  <el-option label="年结" value="year" />
                </el-select>
              </el-form-item>
              <el-form-item label="当前账期" class="query-item query-item-3">
                <el-input v-model="queryForm.currentPeriod" placeholder="2024-01" clearable style="width: 110px" />
              </el-form-item>
              <el-form-item label="配置状态" class="query-item query-item-4">
                <el-select v-model="queryForm.configStatus" placeholder="请选择" clearable style="width: 100px">
                  <el-option label="未配置" :value="0" />
                  <el-option label="已配置" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="结算状态" class="query-item query-item-5">
                <el-select v-model="queryForm.settleStatus" placeholder="请选择" clearable style="width: 100px">
                  <el-option label="未结算" :value="0" />
                  <el-option label="已结算" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="确认状态" class="query-item query-item-6">
                <el-select v-model="queryForm.confirmStatus" placeholder="请选择" clearable style="width: 100px">
                  <el-option label="待确认" :value="0" />
                  <el-option label="已确认" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="采集数据状态" class="query-item query-item-7">
                <el-select v-model="queryForm.collectDataStatus" placeholder="请选择" clearable style="width: 100px">
                  <el-option label="有数据" :value="1" />
                  <el-option label="无数据" :value="0" />
                </el-select>
              </el-form-item>
              <el-form-item class="query-item query-item-8">
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

           <!-- 企业列表表格 -->
           <div class="table-wrapper">
             <el-table 
               v-loading="tableLoading" 
               :data="tableData" 
               stripe 
               style="width: 100%"
             >
             <el-table-column prop="shortName" label="企业简称" min-width="150" show-overflow-tooltip />
             <el-table-column prop="settlementCycle" label="结算周期" align="center">
               <template #default="{ row }">
                 <span v-if="row.settlementCycle === 'month'">月结</span>
                 <span v-else-if="row.settlementCycle === 'quarter'">季结</span>
                 <span v-else-if="row.settlementCycle === 'year'">年结</span>
                 <span v-else>{{ row.settlementCycle }}</span>
               </template>
             </el-table-column>
              <el-table-column prop="currentPeriod" label="当前账期" align="center" />
              <el-table-column prop="startDate" label="开始日期" align="center" />
              <el-table-column prop="endDate" label="结束日期" align="center" />
              <el-table-column label="配置状态" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.configStatus === 1 ? 'success' : 'danger'" size="small">
                    {{ row.configStatus === 1 ? '已配置' : '未配置' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="采集数据状态" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.collectDataStatus === 1 ? 'success' : 'danger'" size="small">
                    {{ row.collectDataStatus === 1 ? '有数据' : '无数据' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="结算状态" width="110" align="center">
               <template #default="{ row }">
                 <el-tag :type="row.settleStatus === 1 ? 'success' : 'danger'" size="small">
                   {{ row.settleStatus === 1 ? '已结算' : '未结算' }}
                 </el-tag>
               </template>
             </el-table-column>
              <el-table-column label="确认状态" width="110" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.confirmStatus === 1 ? 'success' : 'info'" size="small">
                    {{ row.confirmStatus === 1 ? '已确认' : '待确认' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="180" align="center">
                <template #default="{ row }">
                  <el-tooltip content="计费配置" placement="top" effect="light">
                    <el-button 
                      type="warning" 
                      link 
                      size="small"
                      @click="handleConfig(row)"
                    >
                      配置
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="导入采集数据" placement="top" effect="light">
                    <el-button 
                      type="danger" 
                      link 
                      size="small"
                      @click="handleImport(row)"
                    >
                      导入
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.settleStatus === 0 && row.configStatus === 1" content="企业结算" placement="top" effect="light">
                    <el-button 
                      type="primary" 
                      link 
                      size="small"
                      @click="handleSettle(row)"
                    >
                      结算
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.settleStatus === 1 && row.confirmStatus === 0" content="确认结算状态" placement="top" effect="light">
                    <el-button 
                      type="success" 
                      link 
                      size="small"
                      @click="handleConfirm(row)"
                    >
                      确认
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="查看结算单详情" placement="top" effect="light">
                    <el-button type="primary" link size="small" @click="handleDetail(row)">详情</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
           </el-table>
           </div>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.pageNum"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 企业计费配置弹窗 -->
    <EnterpriseBillingConfigDialog ref="billingConfigDialog" />
    
    <!-- 企业结算单管理弹窗 -->
    <EnterpriseSettlementDialog ref="settlementDialog" />
  </div>
</template>

<script lang="ts" setup name="SettleWorkbench">
import { reactive, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getLocationTree } from '@/api/settle';
import type { LocationTreeNode } from '@/api/types/location';
import EnterpriseBillingConfigDialog from './components/EnterpriseBillingConfigDialog.vue';
import EnterpriseSettlementDialog from './components/EnterpriseSettlementDialog.vue';


// 企业配置状态数据
const enterpriseStatus = reactive({
  totalCount: 0, // 企业总数量
  unsettledConfigCount: 0, // 未结算配置数量
});

// 当前账期状态数据
const periodStatus = reactive({
  noDataCount: 0, // 无数据数量
  unsettledCount: 0, // 未结算数量
  unconfirmedCount: 0, // 未确认数量
});

// 地点位置相关
const locationLoading = ref(false);
const locationTree = ref<LocationTreeNode[]>([]);
const selectedLocation = ref<LocationTreeNode | null>(null);
const locationTreeProps = {
  children: 'children',
  label: 'name',
};

// 查询表单
const queryForm = reactive({
  shortName: '',
  settlementCycle: '',
  currentPeriod: '',
  configStatus: undefined as number | undefined,
  settleStatus: undefined as number | undefined,
  confirmStatus: undefined as number | undefined,
  collectDataStatus: undefined as number | undefined,
});

// 表格数据
const tableLoading = ref(false);
const tableData = ref<any[]>([]);

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

// 企业计费配置弹窗
const billingConfigDialog = ref(null);

// 企业结算单管理弹窗
const settlementDialog = ref(null);

// 获取企业配置状态数据
const getEnterpriseStatus = () => {
  // TODO: 调用API获取数据
  // 示例数据
  enterpriseStatus.totalCount = 150;
  enterpriseStatus.unsettledConfigCount = 12;
};

// 获取当前账期状态数据
const getPeriodStatus = () => {
  // TODO: 调用API获取数据
  // 示例数据
  periodStatus.noDataCount = 5;
  periodStatus.unsettledCount = 8;
  periodStatus.unconfirmedCount = 15;
};

// 获取地点位置树
const getLocationTreeData = async () => {
  try {
    locationLoading.value = true;
    // TODO: 需要传入正确的tenantId，这里暂时使用示例值
    const tenantId = 1; // 从用户信息或其他地方获取
    const res = await getLocationTree(tenantId);
    if (res.success && res.data) {
      locationTree.value = res.data;
    } else {
      ElMessage.error(res.msg || '获取地点位置失败');
      locationTree.value = [];
    }
  } catch (error) {
    ElMessage.error('获取地点位置失败');
    locationTree.value = [];
  } finally {
    locationLoading.value = false;
  }
};

// 点击地点位置节点
const handleLocationClick = (data: LocationTreeNode) => {
  selectedLocation.value = data;
  // 重置分页
  pagination.pageNum = 1;
  // 加载该地点位置的企业列表
  getEnterpriseList();
};

// 获取企业列表
const getEnterpriseList = () => {
  tableLoading.value = true;
  
  // TODO: 调用真实API获取数据
  // 这里先用示例数据
  setTimeout(() => {
    tableData.value = [
      {
        id: 1,
        shortName: '示例企业A',
        settlementCycle: 'month',
        currentPeriod: '2024-01',
        startDate: '2024-01-01',
        endDate: '2024-01-31',
        configStatus: 1,
        settleStatus: 0,
        confirmStatus: 0,
        collectDataStatus: 1,
        locationId: selectedLocation.value?.id,
      },
      {
        id: 2,
        shortName: '示例企业B',
        settlementCycle: 'quarter',
        currentPeriod: '2024-Q1',
        startDate: '2024-01-01',
        endDate: '2024-03-31',
        configStatus: 0,
        settleStatus: 0,
        confirmStatus: 0,
        collectDataStatus: 0,
        locationId: selectedLocation.value?.id,
      },
      {
        id: 3,
        shortName: '示例企业C',
        settlementCycle: 'month',
        currentPeriod: '2024-01',
        startDate: '2024-01-01',
        endDate: '2024-01-31',
        configStatus: 1,
        settleStatus: 1,
        confirmStatus: 1,
        collectDataStatus: 1,
        locationId: selectedLocation.value?.id,
      },
    ];
    pagination.total = 3;
    tableLoading.value = false;
  }, 500);
};

// 查询
const handleQuery = () => {
  pagination.pageNum = 1;
  getEnterpriseList();
};

// 重置
const handleReset = () => {
  queryForm.shortName = '';
  queryForm.settlementCycle = '';
  queryForm.currentPeriod = '';
  queryForm.configStatus = undefined;
  queryForm.settleStatus = undefined;
  queryForm.confirmStatus = undefined;
  queryForm.collectDataStatus = undefined;
  pagination.pageNum = 1;
  getEnterpriseList();
};

// 点击卡片数据项
const handleCardClick = (type: string) => {
  // 先重置其他筛选条件，保留基础查询条件
  queryForm.shortName = '';
  queryForm.settlementCycle = '';
  queryForm.currentPeriod = '';
  
  // 根据点击的类型设置相应的筛选条件
  switch (type) {
    case 'total':
      // 企业总数量：清除所有状态筛选，显示全部
      queryForm.configStatus = undefined;
      queryForm.settleStatus = undefined;
      queryForm.confirmStatus = undefined;
      queryForm.collectDataStatus = undefined;
      break;
    case 'unsettledConfig':
      // 未结算配置企业数量：筛选未配置的企业
      queryForm.configStatus = 0;
      queryForm.settleStatus = undefined;
      queryForm.confirmStatus = undefined;
      queryForm.collectDataStatus = undefined;
      break;
    case 'noData':
      // 无采集数据企业数量：筛选无数据的企业
      queryForm.collectDataStatus = 0;
      queryForm.configStatus = undefined;
      queryForm.settleStatus = undefined;
      queryForm.confirmStatus = undefined;
      break;
    case 'unsettled':
      // 未结算企业数量：筛选未结算的企业
      queryForm.settleStatus = 0;
      queryForm.configStatus = undefined;
      queryForm.confirmStatus = undefined;
      queryForm.collectDataStatus = undefined;
      break;
    case 'unconfirmed':
      // 未确认企业数量：筛选待确认的企业
      queryForm.confirmStatus = 0;
      queryForm.configStatus = undefined;
      queryForm.settleStatus = undefined;
      queryForm.collectDataStatus = undefined;
      break;
    default:
      break;
  }
  
  // 重置分页并触发查询
  pagination.pageNum = 1;
  getEnterpriseList();
};


// 分页-每页数量变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageNum = 1;
  getEnterpriseList();
};

// 分页-当前页变化
const handleCurrentChange = (val: number) => {
  pagination.pageNum = val;
  getEnterpriseList();
};

// 配置
const handleConfig = (row: any) => {
  // 打开企业计费配置弹窗
  if (billingConfigDialog.value) {
    billingConfigDialog.value.openDialog({
      id: row.id,
      shortName: row.shortName,
      currentPeriod: row.currentPeriod,
      tenantId: 1 // 这里应该从实际的企业数据中获取tenantId
    });
  }
};

// 导入
const handleImport = (row: any) => {
  ElMessage.info(`正在为企业"${row.shortName}"准备导入功能`);
  // TODO: 实现导入功能
  // 可以打开导入弹窗或跳转到导入页面
};

// 结算
const handleSettle = (row: any) => {
  // 检查配置状态
  if (row.configStatus !== 1) {
    ElMessage.warning('只有"已配置"的企业才能进行结算');
    return;
  }
  
  ElMessageBox.confirm(
    `确定对企业"${row.shortName}"进行结算吗？`,
    '结算确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // TODO: 调用结算API
    ElMessage.success('结算成功');
    getEnterpriseList();
  }).catch(() => {
    // 取消操作
  });
};

// 详情
const handleDetail = (row: any) => {
  // 打开企业结算单管理弹窗
  if (settlementDialog.value) {
    settlementDialog.value.openDialog({
      id: row.id,
      shortName: row.shortName,
      currentPeriod: row.currentPeriod,
      tenantId: 1 // 这里应该从实际的企业数据中获取tenantId
    });
  }
};

// 确认
const handleConfirm = (row: any) => {
  ElMessageBox.confirm(
    `确定确认企业"${row.shortName}"的结算信息吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // TODO: 调用确认API
    ElMessage.success('确认成功');
    getEnterpriseList();
  }).catch(() => {
    // 取消操作
  });
};

// 页面加载时获取数据
onMounted(() => {
  getEnterpriseStatus();
  getPeriodStatus();
  getLocationTreeData();
});
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - $headerHeight - 38px - 40px);
}

.settle-workbench {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.workbench-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  flex-shrink: 0;
}

.card-item {
  background: #FFFFFF;
  border-radius: 4px;
  border: 1px solid #E4E7ED;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.card-1 {
  flex: 0 0 40%;
}

.card-2 {
  flex: 0 0 60%;
}

.card-header-h1,
.card-header-h2 {
  padding: 6px 8px;
  border-bottom: 1px solid #E4E7ED;
  background: #04CEA3;
  
  .card-title {
    font-size: 16px;
    font-weight: 700;
    color: #ffffff;
  }
}

.card-content {
  padding: 12px 24px;
}

.data-row {
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 12px;
}

.data-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 20px;
  border-radius: 4px;
  background: #e9fafc;
  transition: all 0.2s ease;
  cursor: pointer;
  
  &:hover {
    background: #dcdfe6;
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.data-label {
  font-size: 14px;
  color: #000000;
  font-weight: 550;
  white-space: nowrap;
}

.data-value {
  font-size: 16px;
  font-weight: 800;
  color: #f72323;
  margin-left: auto;
  
  &.normal {
    color: #403e3e;
  }
}

// 企业信息区域
.enterprise-section {
  position: relative;
  flex: 1;
  overflow: hidden;
}

.el-tree {
  margin-top: 10px;
  font-size: 14px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 8px;
  
  .el-button {
    margin-left: 8px;
  }
}

.manage-left {
  position: absolute;
  width: 160px;
  padding-right: 10px;
  border-right: 1px solid #efefef;
  height: 100%;
  top: 0;
  left: 0;
  bottom: 0;
  overflow-y: auto;
  overflow-x: hidden;
  
  .el-label {
    font-size: 14px;
    font-weight: 600;
  }
  
  i {
    font-size: 16px;
  }
  
  .empty-state {
    text-align: center;
    padding: 20px 10px;
    color: #909399;
    font-size: 14px;
    
    p {
      margin: 0;
    }
  }
}

.manage-right {
  margin-left: 160px;
  padding-left: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.query-wrapper {
  margin-bottom: 16px;
}

.table-wrapper {
  overflow-x: auto;
  flex: 1;
  
  &::-webkit-scrollbar {
    height: 8px;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 4px;
    
    &:hover {
      background-color: #c0c4cc;
    }
  }
  
  &::-webkit-scrollbar-track {
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  
  :deep(.el-form-item) {
    margin-bottom: 4;
  }
  
  :deep(.el-input),
  :deep(.el-select) {
    transition: width 0.3s ease;
  }
}

$query-mr: (
  1: 12px,
  2: 12px,
  3: 12px,
  4: 12px,
  5: 12px,
  6: 12px,
  7: 12px,
  8: 18px
);

.query-item {
  margin-right: 0; 
  @each $n, $val in $query-mr {
    &.query-item-#{$n} { margin-right: $val; }
  }
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

// 自定义tooltip样式 - 灰底白字
:deep(.el-tooltip__popper) {
  background-color: #57585a !important;
  color: #ffffff !important;
  border: 1px solid #606266 !important;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  
  .el-tooltip__arrow::before {
    background-color: #606266 !important;
    border: 1px solid #606266 !important;
  }
}

</style>